// pages/search/search.js
import request from '../../utils/request'
let isSearch=false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeholderContext: '',
    hotList: [],
    searchContent: "",
    searchList:[],
    historyList:[]
  },
  clearINput(){
    this.setData({
      searchContent:'',
      searchList:[]
    })
  },
  handlerSearchContent(event) {
    let searchContent = event.detail.value.trim()
    this.setData({
      searchContent
    })
    if(isSearch){
      return
    }
    isSearch = true
    setTimeout(()=>{
      isSearch=false
    },200)
    this.getSearchList(searchContent)
  },
  async getSearchList(keywords) {
    if(!keywords){
      this.setData({searchList:[]})
      return
    }
    let {historyList} = this.data
    let isExistHistory = historyList.indexOf(keywords)
    if(isExistHistory != -1){
      historyList.splice(isExistHistory,1)
    }
    historyList.unshift(keywords);

    this.setData({historyList})
    wx.setStorageSync('historyList', historyList)
    let res = await request('search', {
      keywords,
      limit : 10
    });
    this.setData({
      searchList:res.result.songs
    })
  },

  getHistoryList(){
    let historyList =wx.getStorageSync('historyList')
    if(historyList){
      this.setData({historyList})
    }
  },

  deleteHistory(){
    wx.showModal({
      title: '删除',
      content: '亲，您要删除吗？',
      success: (res)=> {
        if (res.confirm) {
          this.setData({historyList:[]})
          wx.removeStorageSync('historyList')
        }
      }
    })
    
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getSearchDefaultContent()
    this.getHistoryList()
  },
  async getSearchDefaultContent() {
    let res = await request('search/default')
    let res1 = await request('search/hot/detail')
    this.setData({
      placeholderContext: res.data.realkeyword,
      hotList: res1.data
    })
    // console.log(res1);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})